package rs.webnet.android.kamere.data;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.util.ArrayList;

import rs.webnet.android.kamere.util.FileResource;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;

import android.content.Context;
import android.util.Log;

public class DataFetcher {
	public static ArrayList<Point> cameras;
	public static ArrayList<Point> roadReport;

	public static boolean initData(Context context) {
		roadReport = getRoadReports(context);
		cameras = getCameras(context);
		return true;
	}

	public static boolean initCameras(Context context) {
		if(cameras==null){
			cameras = getCameras(context);
			Log.d("d","kamere: "+cameras.size());
			return true;
		}
		return false;
	}

	public static boolean initReport(Context context) {
		if (roadReport == null) {
			roadReport = getRoadReports(context);
			return true;
		}
		return false;
	}

	private static ArrayList<Point> getRoadReports(Context context) {
		FileResource fr = new FileResource(context);
		fr.setLink("http://webnet.rs/android/kamere/parse.php");
		fr.connect();
		String data = fr.getData();

		Gson gson = new Gson();
		Type collectionType = new TypeToken<ArrayList<Point>>() {
		}.getType();
		roadReport = new ArrayList<Point>();
		roadReport = gson.fromJson(data, collectionType);
		return roadReport;
	}

	public static ArrayList<Point> getCameras(Context context) {
		InputStream is;
		String data = "";
		try {
			is = context.getAssets().open("kamere.json");
			Gson gson = new Gson();
			//
			DataInputStream dis = new DataInputStream(is);
			BufferedReader br = new BufferedReader(new InputStreamReader(is));
			String strLine;

			// Read File Line By Line
			while ((strLine = br.readLine()) != null) {
				data += strLine;
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Gson gson = new Gson();
		Type collectionType = new TypeToken<ArrayList<Point>>() {
		}.getType();
		cameras = new ArrayList<Point>();
		cameras = gson.fromJson(data, collectionType);
		cameras.get(0).toString();
		return cameras;
	}
}
